package com.gitee.wsl.common.more.ext.glide.transform.gray

import android.annotation.SuppressLint
import android.graphics.Bitmap
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.gitee.wsl.common.more.ext.glide.GlideExt
import com.gitee.wsl.common.more.ext.glide.GlideImageLoadScope
import com.gitee.wsl.jvm.ext.base.UTF8
import java.security.MessageDigest

class GrayPicTransform : BitmapTransformation() {
    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        return convertGreyImg(toTransform)
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }

    override fun equals(o: Any?): Boolean {
        return o is GrayPicTransform
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }

    companion object {
        private const val ID = "com.bumptech.glide.transformations.GrayPicTransform"
        private val ID_BYTES = ID.toByteArray(UTF8)

        /**
         * 彩图转换成灰色图片
         *
         * @param img
         * @return
         */
        fun convertGreyImg(img: Bitmap): Bitmap {
            val width = img.width //获取位图的宽
            val height = img.height //获取位图的高
            val pixels = IntArray(width * height) //通过位图的大小创建像素点数组
            img.getPixels(pixels, 0, width, 0, 0, width, height)
            for (i in 0 until height) {
                for (j in 0 until width) {
                    var grey: Int = if (pixels[width * i + j] == 0) {
                        continue
                    } else pixels[width * i + j]
                    val alpha = grey and -0x1000000
                    val red = grey and 0x00FF0000 shr 16
                    val green = grey and 0x0000FF00 shr 8
                    val blue = grey and 0x000000FF
                    grey =
                        (red.toFloat() * 0.3 + green.toFloat() * 0.59 + blue.toFloat() * 0.11).toInt()
                    grey = alpha or (grey shl 16) or (grey shl 8) or grey
                    pixels[width * i + j] = grey
                }
            }
            //创建空的bitmap时，格式一定要选择ARGB_4444,或ARGB_8888,代表有Alpha通道，RGB_565格式的不显示灰度
            val result: Bitmap = GlideExt.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            result.setPixels(pixels, 0, width, 0, 0, width, height)
            return result
        }
    }
}


@SuppressLint("CheckResult")
fun GlideImageLoadScope.gray(){
    requestOptions.transform(GrayPicTransform())
}